'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: jwt_service.py
* @Time: 2025/10/10
* @All Rights Reserve By Brtc
'''
import os
from dataclasses import dataclass
from typing import Any

import jwt
from injector import inject

from internal.exception.exception import UnauthorizedException


@inject
@dataclass
class JwtService:
    """Jwt 服务"""
    @classmethod
    def generate_token(cls, payload:dict[str, Any])->str:
        """根据传递的载荷信息生成token信息"""
        secret_key = os.getenv("JWT_SECRET_KEY")
        return jwt.encode(payload, secret_key, algorithm="HS256")

    @classmethod
    def parse_token(cls, token:str)->dict[str, Any]:
        """解析传入的token信息得到载荷"""
        secret_key = os.getenv("JWT_SECRET_KEY")
        try:
            return jwt.decode(token, secret_key, algorithms=["HS256"])
        except jwt.exceptions.ExpiredSignatureError:
            raise UnauthorizedException("授权凭证已经过期！")
        except jwt.InvalidTokenError:
            raise UnauthorizedException("Token解析出错,请重新登录")
        except Exception as e:
            raise UnauthorizedException(str(e))